import {
  observable,
  computed,
  action
} from 'mobx';

class appleStore {
  @observable apples = [];
  @observable newAppleId = 0;
  @observable isPicking = false;
  @observable buttonText = '摘苹果';

  @computed get status() {
    let status = {
      appleNow: {
        quantity: 0,
        weight: 0
      },
      appleEaten: {
        quantity: 0,
        weight: 0
      }
    };
    this.apples.forEach(apple => {
      let selector = apple.isEaten ? 'appleEaten' : 'appleNow';
      status[selector].quantity ++;
      status[selector].weight += apple.weight
    });
    return status
  }

  @action pickApple = () => {
    if (this.isPicking) {
      return;
    }

    this.isPicking = true;
    this.buttonText = '正在采摘...';
    setTimeout(() => {
      let weight = Math.floor(200 + Math.random() * 50);
      this.isPicking = false;
      this.buttonText = '摘苹果';
      this.apples.push({
        id: this.newAppleId++,
        weight,
        isEaten: false
      })
    }, 1000)
  }

  @action eatApple = (appleId) => {
    let targetIndex = '';
    this.apples.forEach((apple, index) => {
      if (apple.id === appleId) {
        targetIndex = index
      }
    })
    this.apples[targetIndex].isEaten = true
  }
}

export default appleStore;
